package ext.tianma.part.forms;

import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.apache.log4j.Logger;

import com.ptc.windchill.enterprise.part.commands.PartDocServiceCommand;

import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.com.workflow.WorkflowUtil;
import ext.generic.part.CusIBAUtil;
import ext.tianma.part.MyPartUtil;
import ext.tianma.part.PartWorkflowUtil;
import ext.tianma.part.util.updateIBAValues.ClassificationSynchronization;
import wt.configuration.TraceCode;
import wt.doc.WTDocument;
import wt.doc.WTDocumentMaster;
import wt.enterprise.RevisionControlled;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.collections.WTArrayList;
import wt.iba.value.litevalue.LiteIBAReferenceable;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.State;
import wt.log4j.LogR;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.part.LineNumber;
import wt.part.Quantity;
import wt.part.WTPart;
import wt.part.WTPartConfigSpec;
import wt.part.WTPartDescribeLink;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartStandardConfigSpec;
import wt.part.WTPartUsageLink;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.VersionControlHelper;
import wt.vc.config.ConfigException;
import wt.vc.config.ConfigSpec;
import wt.vc.config.LatestConfigSpec;
import wt.vc.struct.StructHelper;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;
import wt.vc.views.ViewReference;
import wt.vc.wip.WorkInProgressHelper;

public class TransitFactoryUtil implements RemoteAccess {
	/** Log4j Logger. */
	private static final Logger LOGGER = LogR.getLogger(TransitFactoryUtil.class.getName());

	private static final String D_VIEW = "Design";

	private static final String CLASSNAME = TransitFactoryUtil.class.getName();

	private static final String NEW_PRODUCT = "NewProduct";

	private static final String MASS_PRODUCTION_RELEASE = "MassProductionRelease";

	private static final String INWORK = "INWORK";

	private static final String APPROVAL = "APPROVAL";
	// 物料生效地
	private static final String PART_NUMBER_EFFECTIVE_SITE = "partNumberEffectiveSite";
	// 物料发布状态
	private static final String PART_RELESE_STATUS = "partReleaseStatus";
	// BOM发布状态
	private static final String BOM_RELEASE_STATUS = "bomReleaseStatus";

	// 试产
	private static final String TRIAL_PRODUCTION = "TrialProduction";
	// 小批量
	private static final String CUSTOMER_SAMPLE = "CustomerSample";
	// 风险批量
	private static final String RISK_ORDER = "RiskOrder";
	
	// 成品的模组产地
	private static final String MODULEORIGIN = "moduleOrigin";
	private static List<String> rawMaterialStateList = new ArrayList<String>();

	static {
		rawMaterialStateList.add(APPROVAL);
		rawMaterialStateList.add(MASS_PRODUCTION_RELEASE);
		rawMaterialStateList.add(NEW_PRODUCT);
		rawMaterialStateList.add(INWORK);
		rawMaterialStateList.add(TRIAL_PRODUCTION);
		rawMaterialStateList.add(CUSTOMER_SAMPLE);
		rawMaterialStateList.add(RISK_ORDER);
	}

	/**
	 * 通过设计视图版本的零部件和料号生效产地属性，新建多个视图版本
	 * 
	 * 主要用于料号申请流程走完后，按料号生效地产生对应产地的物料
	 * 
	 * @param pbo
	 */
	public static void createMultViewVersionByDPart(Object pbo) {

		if (pbo != null && pbo instanceof WTPart) {
			WTPart dPart = (WTPart) pbo;
			String dPartViewName = dPart.getViewName();
			if (D_VIEW.equals(dPartViewName)) {
				// setTotalToSourcing(dPart);
				try {
					Vector partNumberEffectiveSite = IBAUtil.getIBAValue2(dPart, PART_NUMBER_EFFECTIVE_SITE);

					LOGGER.debug("Debug   partNumberEffectiveSite:" + CLASSNAME + partNumberEffectiveSite.toString());
					if (partNumberEffectiveSite != null) {

						int partNumberEffectiveSiteSize = partNumberEffectiveSite.size();
						String[] factorys = new String[partNumberEffectiveSiteSize];

						for (int i = 0; i < partNumberEffectiveSiteSize; i++) {
							Object obj = partNumberEffectiveSite.get(i);

							if (obj != null && obj instanceof String) {
								factorys[i] = (String) obj;
							}
						}

						tansitFactory(dPart, factorys);
					}
				} catch (RemoteException e) {
					e.printStackTrace();
				} catch (WTException e) {
					e.printStackTrace();
				} finally {

				}
			}
		}
	}

	/**
	 * @author xuge_ning 分类属性传sourcing
	 *         SurfaceStructTypeD-SizeT-Color-partApplicationReason-isSecondSupplier-partSupplier
	 *         SurfaceStructTypeD-SizeT-Color-partApplicationReason-isSecondSupplier-partSupplier
	 *         begin
	 */
	public static void setTotalToSourcing(WTPart part) {
		// getClassNodesByPart(part);
		try {
			LOGGER.debug(CLASSNAME + " <<< Part "
					+ ((LiteIBAReferenceable) (IBAUtil.getIBAValue(part, "Part"))).getIBAReferenceableDisplayString());
			String classificationNode = ((LiteIBAReferenceable) IBAUtil.getIBAValue(part, "Part"))
					.getIBAReferenceableDisplayString();
			String totalToSourcing1 = (String) IBAUtil.getIBAValue(part, "TotalToSourcing");
			LOGGER.debug(CLASSNAME + " <<< Part " + classificationNode);
			LOGGER.debug(CLASSNAME + " TotalToSourcing " + IBAUtil.getIBAValue(part, "TotalToSourcing"));
			LOGGER.debug(CLASSNAME + " <<< totalToSourcing " + totalToSourcing1);
			System.out
					.println(CLASSNAME + " <<< SurfaceStructTypeD " + IBAUtil.getIBAValue(part, "SurfaceStructTypeD"));
			LOGGER.debug(CLASSNAME + " <<< SizeT " + IBAUtil.getIBAValue(part, "SizeT"));
			LOGGER.debug(CLASSNAME + " <<< Color " + IBAUtil.getIBAValue(part, "Color"));
			LOGGER.debug(
					CLASSNAME + " <<< partApplicationReason " + IBAUtil.getIBAValue(part, "partApplicationReason"));
			LOGGER.debug(CLASSNAME + " <<< isSecondSupplier " + IBAUtil.getIBAValue(part, "isSecondSupplier"));
			LOGGER.debug(CLASSNAME + " <<< partSupplier " + IBAUtil.getIBAValue(part, "partSupplier"));
			LOGGER.debug(CLASSNAME + " <<< getCreatorFullName " + part.getCreatorFullName());
			LOGGER.debug(
					CLASSNAME + " <<< partApplicationReason " + IBAUtil.getIBAValue(part, "partApplicationReason"));

			if (classificationNode != null && !"".equals(classificationNode)) {
				String totalToSourcing = (String) IBAUtil.getIBAValue(part, "TotalToSourcing");
				if (totalToSourcing != null && !"".equals(totalToSourcing)) {

					String[] paramList = totalToSourcing.split("-");
					StringBuffer valueList = new StringBuffer("");
					int length = paramList.length;
					if (length > 0) {
						for (int i = 0; i < length; i++) {
							String param = paramList[i].trim();
							if (param != null && !"".equals(param)) {
								String paramValue = (String) IBAUtil.getIBAValue(part, param);
								if (paramValue != null && !"".equals(paramValue)) {
									if (valueList.length() <= 0) {
										valueList.append(paramValue);
									} else {
										valueList.append(paramValue + "-");
									}
								}
							}
						}
						String creator = part.getCreatorFullName();
						valueList.append(creator);
					}
					LOGGER.debug(CLASSNAME + " <<< valueList " + valueList);
					IBAUtil.forceSetIBAValue(part, "classToSourcing", valueList.toString());
					LOGGER.debug(CLASSNAME + " classToSourcing " + IBAUtil.getIBAValue(part, "classToSourcing"));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * end
	 */

	/**
	 * 零部件转厂，包含零部件本身和他结构下的所有子件
	 * 
	 * @param part
	 * @param factorys
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static void tansitPartAndChildrenFactory(WTPart part, String[] factorys)
			throws WTException, RemoteException {
		if (part == null) {
			return;
		}

		// 判断是否选择物料生效地
		if (factorys == null || factorys.length == 0) {
			throw new WTException("没有选择物料生效地请选择！");
		}
		if (TMTypeUtil.isRawMaterial2(part)) {
			// String partNumberEffectiveSite = (String) IBAUtil.getIBAValue(part,
			// "partNumberEffectiveSite");
			Vector partNumberEffectiveSite = IBAUtil.getIBAValue2(part, PART_NUMBER_EFFECTIVE_SITE);

			LOGGER.debug("Debug   partNumberEffectiveSite:" + CLASSNAME + partNumberEffectiveSite.toString());
			System.out.println("partNumberEffectiveSite=====>>>" + partNumberEffectiveSite);
			if (partNumberEffectiveSite != null && partNumberEffectiveSite.contains("F13")) {
				String partCNAndENName = "";
				String departments = "";
				partCNAndENName = (String) IBAUtil.getIBAValue(part, "partCNAndENName");
				System.out.println("partCNAndENName===>>" + partCNAndENName);
				if (("tape -- 单面胶带").equals(partCNAndENName) || ("tape -- 泡棉胶带").equals(partCNAndENName)
						|| ("tape -- 粘合胶带").equals(partCNAndENName) || ("tape -- 导电胶带").equals(partCNAndENName)
						|| ("tape -- 绝缘胶带").equals(partCNAndENName) || ("tape -- 遮光胶带").equals(partCNAndENName)
						|| ("Protective film -- 保护膜").equals(partCNAndENName)
						|| ("tape -- 双面导电胶带").equals(partCNAndENName)) {
					departments = (String) IBAUtil.getIBAValue(part, "departments");
					System.out.println("departments======>>>" + departments);
					if (departments == null || departments.isEmpty()) {
						throw new WTException("请选择所属部门！");
					}
				}

			}
		}

		List<WTPart> checkInPartList = new ArrayList<WTPart>();

		try {
			List<WTPart> allPartList = new ArrayList<WTPart>();

			// 将主料加入列表中
			allPartList.add(part);

			// 获取主料所有的子件，并加入列表
			allPartList = getAllSubPart(part, allPartList);
			List<WTPartUsageLink> usageList = getAllUsageLink(part);

			LOGGER.debug("Debug   usageList:" + usageList);
			// 检查所有子件的生命周期状态是否符合要求 2013-11-14
			StringBuffer stbPartLog = new StringBuffer();
			checkAllSubPartState(allPartList, stbPartLog);
			if (stbPartLog.length() > 0) {
				throw new WTException(stbPartLog + "状态不符合要求，无法进行转厂！");
			}

			// 执行批量转厂操作
			tansitFactory(allPartList, factorys);
			// 重新构造新视图下的usageLink关系
			createPartUsageLink(part, usageList, factorys, checkInPartList);
			// 转厂完成后自动创建DescriptionLink
			createDescriptionLinkForTransitFactory(part);
			// 重新构造替代料与新的usageLink关系
		} catch (RemoteException e) {
			e.printStackTrace();
		} finally {
			checkInAllPart(checkInPartList);
		}
	}

	/**
	 * 转厂完成后自动创建DescriptionLink
	 * 
	 * @author he_zhang2
	 * @param targetObj
	 * @param eventType
	 * @return
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static void createDescriptionLinkForTransitFactory(WTPart part) throws WTException, RemoteException {
		WTDocument doc = null;
		QueryResult qr = PartDocServiceCommand.getAssociatedDescribeDocuments(part);
		if (qr != null && qr.hasMoreElements()) {
			doc = (WTDocument) qr.nextElement();
			if (TMTypeUtil.isATypeObject(doc, ".ControlDocument")) {
				/**
				 * 过滤历史数据
				 */
				WTDocumentMaster docMaster = (WTDocumentMaster) doc.getMaster();
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				Timestamp createDateTime = docMaster.getCreateTimestamp();
				String createDate = null;
				String item = null;
				if (null != createDateTime) {
					createDate = format.format(createDateTime);
				}
				if (null != createDate) {
					// 创建时间比2018-10-10前
					if ("2018-12-01".compareTo(createDate) < 0) {
						if (null != IBAUtil.getIBAValue(doc, "Item")) {
							item = ((String) IBAUtil.getIBAValue(doc, "Item")).trim();
						}
						if (item != null) {
							// 获取物料的Design视图对象
							WTPart dpart = null;
							dpart = (WTPart) CoreUtil.getWTPartByNumberAndView(item, "Design");
							// 获取物料的其他所有视图对象
							WTArrayList partList = new WTArrayList();
							partList = PartWorkflowUtil.getAllPartViews(dpart);
							partList.add(dpart);
							// 创建DescriptionLink
							for (int i = 0; i < partList.size(); i++) {
								WTPart wtpart = null;
								wtpart = (WTPart) partList.getPersistable(i);
								WTPartDescribeLink link = WTPartDescribeLink.newWTPartDescribeLink(wtpart, doc);
								PersistenceServerHelper.manager.insert(link);
							}
						}
					}
				}
			}
		}
	}

	/**
	 * 重构新视图下的结构
	 * 
	 * @param part
	 * @param usageList
	 * @param factorys
	 * @throws WTException
	 */
	private static void createPartUsageLink(WTPart part, List<WTPartUsageLink> usageList, String[] factorys,
			List<WTPart> checkInPartList) throws WTException {
		if (!isDesignPart(part)) {

			if (factorys != null) {

				for (int i = 0; i < factorys.length; i++) {
					String viewName = factorys[i];

					if (viewName != null) {
						createPartUsageLink(usageList, viewName, checkInPartList);
					}
				}
			}
		}
	}

	/**
	 * 重新构建usageLink关系
	 * 
	 * @param part
	 * @param usageList
	 */
	private static void createPartUsageLink(List<WTPartUsageLink> usageList, String viewName,
			List<WTPart> checkInPartList) {

		if (usageList == null) {
			return;
		}

		try {
			Iterator<WTPartUsageLink> iterator = usageList.iterator();
			while (iterator.hasNext()) {
				WTPartUsageLink wtPartUsageLink = iterator.next();

				if (wtPartUsageLink != null) {
					WTPart parent = wtPartUsageLink.getUsedBy();
					WTPart newParent = CoreUtil.getWTPartByMasterAndView((WTPartMaster) parent.getMaster(), viewName);

					if (newParent != null) {

						if (partUsageLinkiIsExisted(wtPartUsageLink, newParent)) {
							LOGGER.debug("Debug   partUsageLinkiIsExisted:"
									+ partUsageLinkiIsExisted(wtPartUsageLink, newParent));
							continue;
						} else {
							// 重新设置usageLink的父件需要检出零部件
							LOGGER.debug("Debug   newParent:" + newParent.getViewName());
							newParent = (WTPart) CoreUtil.checkoutObject(newParent);
							wtPartUsageLink.setUsedBy(newParent);
							PersistenceHelper.manager.save(wtPartUsageLink);
							LOGGER.debug("Debug   checkoutnewParent:" + WorkInProgressHelper.isCheckedOut(newParent));

							if (!checkInPartList.contains(newParent)) {
								checkInPartList.add(newParent);
							}
						}
					}
				}
			}
		} catch (WTException e) {
			e.printStackTrace();
		} catch (WTPropertyVetoException e) {
			e.printStackTrace();
		} finally {

		}
	}

	/**
	 * 检入已检出的对象
	 * 
	 * @param checkInPartList
	 * @throws WTException
	 */
	private static void checkInAllPart(List<WTPart> checkInPartList) throws WTException {

		if (checkInPartList == null || checkInPartList.size() == 0) {
			return;
		}

		Iterator<WTPart> iterator = checkInPartList.iterator();
		while (iterator.hasNext()) {
			WTPart checkInPart = iterator.next();

			if (checkInPart != null) {
				CoreUtil.checkinObject(checkInPart, "转厂之后重新搭建结构");
			}
		}
	}

	/**
	 * 根据一个usageLink创建一个新的usageLink
	 * 
	 * @param wtPartUsageLink
	 * @param newWTPartUsageLink
	 * @throws WTPropertyVetoException
	 * @throws RemoteException
	 * @throws WTException
	 */
	public static void setNewPartUsageLinkQuality(WTPartUsageLink wtPartUsageLink, WTPartUsageLink newWTPartUsageLink)
			throws WTPropertyVetoException, RemoteException, WTException {

		if (wtPartUsageLink == null || newWTPartUsageLink == null) {
			return;
		}

		// 行号
		LineNumber lineNumber = wtPartUsageLink.getLineNumber();
		if (lineNumber != null) {
			newWTPartUsageLink.setLineNumber(lineNumber);
		}
		// 数量单位
		Quantity quantity = wtPartUsageLink.getQuantity();
		if (quantity != null) {
			newWTPartUsageLink.setQuantity(quantity);
		}
		// 追踪代码
		TraceCode traceCode = wtPartUsageLink.getTraceCode();
		if (traceCode != null) {
			newWTPartUsageLink.setTraceCode(traceCode);
		}
		// 检索号
		String findNumber = wtPartUsageLink.getFindNumber();
		if (findNumber != null) {
			newWTPartUsageLink.setFindNumber(findNumber);
		}
		// 位号
		String reference = wtPartUsageLink.getReference();
		if (reference != null) {
			newWTPartUsageLink.setReference(reference);
		}
		// 设置iba属性
		IBAUtil.copyIBAValues(wtPartUsageLink, newWTPartUsageLink);
	}

	/**
	 * 判断指定WTPartUsageLink是否存在
	 * 
	 * @param wtPartUsageLink
	 * @return
	 * @throws WTException
	 * @throws ConfigException
	 */
	private static boolean partUsageLinkiIsExisted(WTPartUsageLink wtPartUsageLink, WTPart newParent)
			throws ConfigException, WTException {
		boolean partUsageLinkiIsExisted = false;

		if (wtPartUsageLink == null) {
			return partUsageLinkiIsExisted;
		}

		List<WTPartUsageLink> listLink = MyPartUtil.getAllLevelUsageLink(newParent);

		if (listLink != null) {

			LOGGER.debug("Debug   listLink:" + listLink.size());
			Iterator<WTPartUsageLink> iterator = listLink.iterator();

			while (iterator.hasNext()) {
				WTPartUsageLink newPartUsageLink = iterator.next();

				if (newPartUsageLink != null) {
					partUsageLinkiIsExisted = partUsageLinkiIsExisted(wtPartUsageLink, newPartUsageLink);
					LOGGER.debug("Debug   newPartUsageLink...partUsageLinkiIsExisted:" + partUsageLinkiIsExisted);
					if (partUsageLinkiIsExisted) {
						break;
					}
				}
			}
		}
		LOGGER.debug("Debug   partUsageLinkiIsExisted:" + partUsageLinkiIsExisted);
		return partUsageLinkiIsExisted;
	}

	/**
	 * 通过LineNumber,子件Master判断两个对象是否相同
	 * 
	 * @param wtPartUsageLink
	 * @param newPartUsageLink
	 * @return
	 */
	private static boolean partUsageLinkiIsExisted(WTPartUsageLink wtPartUsageLink, WTPartUsageLink newPartUsageLink) {
		boolean partUsageLinkiIsExisted = false;

		if (wtPartUsageLink == null || newPartUsageLink == null) {
			return partUsageLinkiIsExisted;
		}
		// 位号
		String wtPartLinkNumber = getLinkNumber(wtPartUsageLink);
		String newPartLinkNumber = getLinkNumber(newPartUsageLink);
		// 子件Master
		WTPartMaster wtPartMaster = wtPartUsageLink.getUses();
		WTPartMaster newPartMaster = newPartUsageLink.getUses();

		if (wtPartLinkNumber.equals(newPartLinkNumber)) {

			if (PersistenceHelper.isEquivalent(wtPartMaster, newPartMaster)) {

				partUsageLinkiIsExisted = true;
			}
		}

		return partUsageLinkiIsExisted;
	}

	/**
	 * 获取usageLink的number
	 * 
	 * @param usageLink
	 * @return
	 */
	private static String getLinkNumber(WTPartUsageLink usageLink) {
		String lineNumber = "";

		if (usageLink == null) {
			return lineNumber;
		}
		LineNumber pLineNumber = usageLink.getLineNumber();
		if (pLineNumber != null) {
			lineNumber = pLineNumber.getValue() + "";
		}

		return lineNumber;
	}

	/**
	 * 判断零部件视图是否为“Design”
	 * 
	 * @param part
	 * @return
	 */
	private static boolean isDesignPart(WTPart part) {
		boolean isDesignPart = false;

		if (part == null) {
			return isDesignPart;
		}

		String view = part.getViewName();

		if (D_VIEW.equals(view)) {
			isDesignPart = true;
		}
		return isDesignPart;
	}

	/**
	 * 获取指定零部件的所有usageLink
	 * 
	 * @param part
	 * @return
	 */
	private static List<WTPartUsageLink> getAllUsageLink(WTPart part) {
		List<WTPartUsageLink> usageLinkList = new ArrayList<WTPartUsageLink>();

		if (part != null) {

			usageLinkList = MyPartUtil.getAllUsageLink(part);

		}

		return usageLinkList;
	}

	/**
	 * 零部件批量转厂，包括List列表中的所有零部件
	 * 
	 * @param partList
	 * @param factorys
	 * @throws RemoteException
	 * @throws WTException
	 */
	public static void tansitFactory(List<WTPart> partList, String[] factorys) throws RemoteException, WTException {
		if (partList == null) {
			return;
		}

		Iterator<WTPart> partListIte = partList.iterator();
		WTPart aPart = null;
		while (partListIte.hasNext()) {
			aPart = partListIte.next();

			tansitFactory(aPart, factorys);
		}
	}

	/**
	 * 零部件转厂
	 * 
	 * @param part
	 *            需要转厂的零部件
	 * @param factorys
	 *            需要生效的物料生效地
	 * @throws RemoteException
	 * @throws WTException
	 */
	public static void tansitFactory(WTPart part, String[] factorys) throws RemoteException, WTException {
		if (part == null) {
			return;
		}

		// 获取设计视图最新版本
		WTPart dPart = CoreUtil.getWTPartByMasterAndView((WTPartMaster) part.getMaster(), D_VIEW);

		if (dPart == null) {
			throw new WTException("零部件" + part.getDisplayIdentifier() + "没有" + D_VIEW + "视图的版本");
		}

		if (factorys == null) {
			return;
		}

		List<String> newFactoryList = new ArrayList<String>();

		try {
			if (!TMTypeUtil.isTwoLevelMaterial(dPart) && !TMTypeUtil.isBLU(dPart) && !TMTypeUtil.isFPC_PCB(dPart)) {
				// 不是二级物料的时候需要做转厂以及拷贝IBA属性
				for (int i = 0; i < factorys.length; i++) {
					if (factorys[i] != null) {
						factorys[i] = factorys[i].trim();

						if (!factorys[i].equals("")) {
							// 执行转视图操作
							WTPart newViewPart = tansitView(dPart, factorys[i], newFactoryList,
									part.getLifeCycleState());

							if (newViewPart != null) {
								// 部分IBA属性不做拷贝，例如：物料生效地
								copyIBAValues(dPart, newViewPart);

							}
						}
					}
				}
			} else {
				// 是二级物料的时候只需要跟新物料生效地
				for (int i = 0; i < factorys.length; i++) {
					if (factorys[i] != null) {
						factorys[i] = factorys[i].trim();

						if (!factorys[i].equals("")) {
							newFactoryList.add(factorys[i]);
						}
					}
				}
			}

		} finally {
			// 获取设计视图零部件当前的物料生效地
			String dPartEffectiveSite = "";
			Vector vector = IBAUtil.getIBAValue2(dPart, PART_NUMBER_EFFECTIVE_SITE);
			// add kwang 2013-12-09
			if (vector != null) {

				for (int i = 0; i < vector.size(); i++) {
					Object strObject = vector.get(i);

					if (strObject != null) {

						if (dPartEffectiveSite.equals("")) {
							dPartEffectiveSite = (String) strObject;
						} else {
							dPartEffectiveSite = dPartEffectiveSite + "," + (String) strObject;
						}
					}
				}
			}

			LOGGER.debug("Debug   finally...dPartEffectiveSite:" + dPartEffectiveSite);
			setDesignEffectiveSite(dPart, dPartEffectiveSite, newFactoryList);
		}
	}

	/**
	 * 对零部件执行转视图操作
	 * 
	 * @param dPart
	 *            设计视图零部件
	 * @param newFactory
	 *            新视图
	 * @param newFactoryList
	 *            收集新视图的列表
	 * 
	 * @return WTPart 转视图后生成的零部件新视图版本
	 */
	private static WTPart tansitView(WTPart dPart, String newFactory, List<String> newFactoryList, State state) {
		WTPart newViewPart = null;

		// dPart必须是Design视图的零部件，才能执行转视图
		if (canTansitView(dPart)) {
			boolean flag = SessionServerHelper.manager.setAccessEnforced(false);

			try {
				WTPart aPart = CoreUtil.getWTPartByMasterAndView((WTPartMaster) dPart.getMaster(), newFactory);

				// 如果可以获取newFactory视图的零部件，则说明此产地的零部件已经存在，不必再重新转视图
				if (aPart != null) {
					String aPartView = aPart.getViewName();

					if ((!aPartView.equals(D_VIEW)) && aPartView.equals(newFactory)) {
						newFactoryList.add(newFactory);

						newViewPart = aPart;
						return newViewPart;
					}
				}

				// 根据Design视图的零部件，生成新的视图版本 begin
				newViewPart = (WTPart) ViewHelper.service.newBranchForView(dPart, newFactory);
				// xuge 设置物料的创建者和修改者
				/*
				 * WTPrincipal curUser= SessionHelper.manager.getPrincipal();
				 * WTPrincipalReference dpartPrincipalReference = dPart.getCreator();
				 * LOGGER.debug("dpartPrincipalReference" + dpartPrincipalReference.getName());
				 * 
				 * LOGGER.debug("SessionHelper.manager.getPrincipal" + curUser.getName());
				 * WTPrincipalReference wtprincipalreference =
				 * WTPrincipalReference.newWTPrincipalReference(curUser);
				 * VersionControlHelper.assignIterationCreator(newViewPart,
				 * dpartPrincipalReference);
				 */
				newViewPart = (WTPart) PersistenceHelper.manager.save(newViewPart);
				// VersionControlHelper.setIterationModifier(newViewPart,
				// dpartPrincipalReference);
				/**
				 * end
				 */
				// 新建视图版本成功，将此版本对应的物料生效地添加到List中，以便更新Design视图零部件的物料生效地
				newFactoryList.add(newFactory);

				// 设置生命周期状态为“正在工作”
				newViewPart = (WTPart) LifeCycleHelper.service.setLifeCycleState(newViewPart, State.INWORK);

				// 原材料转厂之后，转完厂的零部件的状态为转厂前的的状态
				if (TMTypeUtil.isRawMaterial(newViewPart)) {
					System.out.println("====>>>原材料转厂《《《======");
					newViewPart = (WTPart) LifeCycleHelper.service.setLifeCycleState(newViewPart, state);

				}
				// 更新新视图零部件的物料生效地
				IBAUtil.forceSetIBAValue(newViewPart, PART_NUMBER_EFFECTIVE_SITE, newFactory);
				/**
				 * @author xuge_ning 成品模组产地枚举值的处理 begin
				 */
				if (TMTypeUtil.isFinishedGood(dPart)) {

					Vector modelOrigin = IBAUtil.getIBAValue2(dPart, MODULEORIGIN);
					LOGGER.debug(CLASSNAME + "模组产地：modelOrigin:" + modelOrigin.toString());
					String model = "";
					if (modelOrigin != null) {
						for (int i = 0; i < modelOrigin.size(); i++) {
							Object obj = modelOrigin.get(i);
							if (obj != null && obj instanceof String) {
								if (model.equals("")) {
									model = (String) obj;
								} else {
									model = model + "," + (String) obj;
								}
							}
						}
						LOGGER.debug(CLASSNAME + "模组产地：model：" + model);
						CusIBAUtil.forceSetEnumIBAValue(newViewPart, MODULEORIGIN, model);
					}
				}
				/**
				 * end
				 */

			} catch (WTException e) {
				e.printStackTrace();
			} catch (WTPropertyVetoException e) {
				e.printStackTrace();
			} catch (RemoteException e) {
				e.printStackTrace();
			} finally {
				SessionServerHelper.manager.setAccessEnforced(flag);
			}
		}

		return newViewPart;
	}

	/**
	 * 判断零部件是否可以执行转视图操作
	 * 
	 * @param dPart
	 * @return
	 */
	private static boolean canTansitView(WTPart dPart) {
		boolean result = true;

		// 零部件不能为null
		if (dPart == null) {
			LOGGER.debug("Warning Info : 用于转厂的目标零部件为NULL对象");

			result = false;
		} else {
			String dPartViewName = dPart.getViewName();

			// 零部件视图必须是Design视图
			if (!D_VIEW.equals(dPartViewName)) {
				LOGGER.debug("Warning Info : 用于转厂的目标零部件为：" + dPart.getDisplayIdentifier());
				LOGGER.debug("Warning Info : 用于转厂的目标零部件不是设计视图的版本，不能执行转厂操作。");

				result = false;
			}
		}

		return result;
	}

	public static void copyIBAValues(WTPart part, WTPart newViewPart) {
		try {
			Hashtable values = IBAUtil.getIBAValues(part);
			copyIBAValues(values, newViewPart);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 同编号不同视图的两个零部件对IBA属性做拷贝
	 * 
	 * @param part
	 * @param newViewPart
	 */
	public static void copyIBAValues(Hashtable values, WTPart newViewPart) {
		try {
			System.out.println("属性同步values=====>>"+values);
			// 物料生效地,物料发布状态和BOM发布状态属性不做拷贝
			if (values.containsKey(PART_NUMBER_EFFECTIVE_SITE)) {
				LOGGER.debug("Info : copyIBAValues method , Hashtable contains " + PART_NUMBER_EFFECTIVE_SITE
						+ ", Remove it from the Hashtable.");
				values.remove(PART_NUMBER_EFFECTIVE_SITE);
			}

			if (values.containsKey(PART_RELESE_STATUS)) {
				LOGGER.debug("Info : copyIBAValues method , Hashtable contains " + PART_RELESE_STATUS
						+ ", Remove it from the Hashtable.");
				values.remove(PART_RELESE_STATUS);
			}

			if (values.containsKey(BOM_RELEASE_STATUS)) {
				LOGGER.debug("Info : copyIBAValues method , Hashtable contains " + BOM_RELEASE_STATUS
						+ ", Remove it from the Hashtable.");
				values.remove(BOM_RELEASE_STATUS);
			}
			if (TMTypeUtil.isFinishedGood(newViewPart) && values.containsKey(MODULEORIGIN)) {
				LOGGER.debug("Info : copyIBAValues method , Hashtable contains " + MODULEORIGIN
						+ ", Remove it from the Hashtable.");
				values.remove(MODULEORIGIN);
			}
			newViewPart=(WTPart) IBAUtil.setSoftTypeIBAValues(newViewPart, values);
			ClassificationSynchronization.getClassification(newViewPart);
		} catch (WTException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 更新设计视图零部件的物料生效地
	 * 
	 * @param part
	 * @param currentEffectiveSite
	 * @param factorys
	 * @throws WTException
	 * @throws RemoteException
	 */
	private static void setDesignEffectiveSite(WTPart dPart, String dPartEffectiveSite, List<String> newFactoryList)
			throws WTException, RemoteException {
		if (dPart == null) {
			return;
		}

		String viewName = dPart.getViewName();

		if (!D_VIEW.equals(viewName)) {
			dPart = CoreUtil.getWTPartByMasterAndView((WTPartMaster) dPart.getMaster(), D_VIEW);

			if (dPart == null) {
				return;
			}
		}

		dPartEffectiveSite = getNewDPartEffectiveSite(dPartEffectiveSite, newFactoryList);

		LOGGER.debug("Debug   dPartEffectiveSite:" + dPartEffectiveSite);
		boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
		try {
			// 检出零部件
			dPart = (WTPart) CoreUtil.checkoutObject(dPart);
			// 更新物料生效地
			// 多值枚举设值
			// IBAUtil.forceSetIBAValue( part , PART_NUMBER_EFFECTIVE_SITE ,
			// currentEffectiveSite ) ;
			CusIBAUtil.forceSetEnumIBAValue(dPart, PART_NUMBER_EFFECTIVE_SITE, dPartEffectiveSite);

		} finally {
			// 检入零部件
			System.out.println("dPart========>>"+dPart.getNumber());
			if (WorkflowUtil.isObjectCheckedOut(dPart)) {
			    // 检入零部件
			    CoreUtil.checkinObject(dPart, "转厂完成");
			}
			SessionServerHelper.manager.setAccessEnforced(flag);
		}

	}

	/**
	 * 根据Design视图的Part本身的料号生效地IBA属性和新的料号生效地List列表，生成新的设计视图料号生效地属性值
	 * 
	 * @param dPartEffectiveSite
	 *            当前Design视图的零部件的料号生效地
	 * @param newFactoryList
	 *            新的料号生效地List列表
	 * 
	 * @return String 新的设计视图料号生效地IBA属性值
	 */
	private static String getNewDPartEffectiveSite(String dPartEffectiveSite, List<String> newFactoryList) {
		if (dPartEffectiveSite == null) {
			dPartEffectiveSite = "";
		}

		// 遍历newFactoryList，将物料生效地中没有的加到currentEffectiveSite中
		if (newFactoryList != null) {
			int size = newFactoryList.size();

			for (int i = 0; i < size; i++) {
				String newFactory = newFactoryList.get(i);

				if (newFactory != null) {
					newFactory = newFactory.trim();

					if (!newFactory.equals("")) {
						if (dPartEffectiveSite.equals("")) {
							dPartEffectiveSite = newFactory;
						} else {
							if (!dPartEffectiveSite.contains(newFactory)) {
								dPartEffectiveSite = dPartEffectiveSite + "," + newFactory;
							}
						}
					}
				}
			}
		}

		return dPartEffectiveSite;
	}

	/**
	 * 检查零部件状态是否符合要求(新品和量产发布)2013-11
	 * 
	 * @param allPartList
	 * 
	 * @return
	 */
	private static void checkAllSubPartState(List<WTPart> allPartList, StringBuffer stbPartLog) {
		if (allPartList != null && allPartList.size() > 0) {
			Iterator<WTPart> iterator = allPartList.iterator();

			while (iterator.hasNext()) {
				WTPart part = iterator.next();

				if (part != null) {

					// 二级物料不做转厂不需要检查状态
					if (!TMTypeUtil.isTwoLevelMaterial(part) && !TMTypeUtil.isBLU(part)
							&& !TMTypeUtil.isFPC_PCB(part)) {
						State partState = part.getLifeCycleState();

						if (partState != null) {
							String state = partState.toString();

							if ((!rawMaterialStateList.contains(state))) {
								stbPartLog.append(part.getNumber());
								stbPartLog.append("\n");
							}
						}
					}
				}
			}
		}
	}

	/**
	 * 获取零部件的所有子件
	 * 
	 * @param part
	 * @param allSubPartList
	 * @return
	 * @throws WTException
	 */
	private static List<WTPart> getAllSubPart(WTPart part, List<WTPart> allSubPartList) throws WTException {
		if (allSubPartList == null) {
			allSubPartList = new ArrayList<WTPart>();
		}

		ConfigSpec latestconfigspec = getConfigSpec(part);

		QueryResult qr = StructHelper.service.navigateUsesToIteration(part, WTPartUsageLink.class, false,
				latestconfigspec);

		while (qr != null && qr.hasMoreElements()) {
			// 每一个element实际是一个persistable数组
			Persistable apersistable[] = (Persistable[]) qr.nextElement();

			Object uses = apersistable[1];

			WTPart subPart = null;
			if (uses instanceof WTPart) {
				subPart = (WTPart) uses;
			} else if (uses instanceof WTPartMaster) {
				WTPartMaster master = (WTPartMaster) uses;

				// 获取最新版本
				subPart = CoreUtil.getWTPartByMasterAndView(master, part.getViewName());
			} else {

			}

			if (subPart != null) {
				// 如果列表中不包含此零部件，则加入列表，并进行递归
				if (!allSubPartList.contains(subPart)) {
					allSubPartList.add(subPart);

					getAllSubPart(subPart, allSubPartList);
				}
			}
		}

		return allSubPartList;
	}

	/**
	 * 
	 * @param part
	 * @return
	 */
	private static ConfigSpec getConfigSpec(WTPart part) {
		ConfigSpec latestconfigspec = new LatestConfigSpec();

		String view = "";
		ViewReference viewRef = part.getView();
		if (viewRef != null) {
			view = viewRef.getName();
		}
		try {
			if (view != null && view.length() > 0) {
				View viewObj = ViewHelper.service.getView(view);
				WTPartConfigSpec config = WTPartHelper.service.findWTPartConfigSpec();
				WTPartStandardConfigSpec standardConfig = config.getStandard();

				standardConfig.setView(viewObj);
				latestconfigspec = standardConfig;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return latestconfigspec;
	}

	/**
	 * 获取对象的大小版本组成的版本序列值，形如： A.1
	 * 
	 * @param revisionControlled
	 * @return
	 */
	private static String getVersion(RevisionControlled revisionControlled) {

		String version = "";

		if (revisionControlled != null) {
			// 获取大版本
			String majorVersion = revisionControlled.getVersionIdentifier().getValue();

			// 获取小版本
			String minorVersion = revisionControlled.getIterationIdentifier().getValue();

			version = majorVersion + "." + minorVersion;
		}

		return version;
	}

	/**
	 * 根据零部件编号，视图和版本获取零部件对象
	 * 
	 * @param number
	 * @param view
	 * @param version
	 * @return
	 * @throws WTException
	 */
	private static WTPart getWTPartByNumViewAndVersion(String number, String view, String version) throws WTException {
		WTPart part = null;

		QuerySpec qs = new QuerySpec(WTPartMaster.class);

		// 定义搜索条件，以零部件编号方式在master中搜索
		SearchCondition sc = new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER, SearchCondition.EQUAL,
				number);
		qs.appendSearchCondition(sc);

		QueryResult qr = PersistenceHelper.manager.find(qs);

		while (qr.hasMoreElements()) {
			WTPartMaster master = (WTPartMaster) qr.nextElement();

			if (master != null) {
				part = getWTPartByNumViewAndVersion(master, view, version);
			}
		}

		return part;
	}

	/**
	 * 根据零部件主数据(master)和视图获取对应最新版本零部件
	 * 
	 * @author WeiWenJie
	 * @param master
	 * @param view
	 * @return
	 * @throws WTException
	 */
	private static WTPart getWTPartByNumViewAndVersion(WTPartMaster master, String view, String version)
			throws WTException {
		WTPart part = null;

		// 获取所有版本的零部件
		QueryResult qr = VersionControlHelper.service.allIterationsOf(master);

		while (qr.hasMoreElements()) {
			part = (WTPart) qr.nextElement();

			// 视图相同，并且版本相同
			if (part.getViewName().equals(view) && getVersion(part).equals(version)) {
				return part;
			}
		}

		return part;
	}

	private static List<WTPart> getAllParentWithDesignView(WTPart wtpart) {
		List<WTPart> parentList = new ArrayList<WTPart>();

		if (wtpart == null) {
			return parentList;
		}

		try {
			WTPartMaster partMaster = (WTPartMaster) wtpart.getMaster();

			QueryResult queryResult = StructHelper.service.navigateUsedBy(partMaster, true);

			if (queryResult != null && queryResult.size() > 0) {
				int i = 0;

				while (queryResult.hasMoreElements()) {
					Object obj = queryResult.nextElement();

					if (obj != null && obj instanceof WTPart) {
						WTPart parent = (WTPart) obj;

						if (parent != null) {
							parent = CoreUtil.getWTPartByNumberAndView(parent.getNumber(), D_VIEW);

							if (!parentList.contains(parent)) {
								parentList.add(parent);
							}
						}
					}
				}
			}
		} catch (WTException wte) {
			wte.printStackTrace();
		}

		return parentList;
	}

	public static void main(String[] args) {

		if (args != null && args.length > 2) {
			LOGGER.debug("Debug    main...");
			try {

				WTPart part = CoreUtil.getWTPartByNumberAndView(args[0], args[1]);

				if (part != null) {

					LOGGER.debug("Debug   part:" + part.getNumber());

					String[] partView = new String[args.length - 2];

					for (int i = 2; i < args.length; i++) {

						partView[i - 2] = args[i];

					}
					if (part != null) {

						if (!RemoteMethodServer.ServerFlag) {

							LOGGER.debug("Debug     RemoteMethodServer...");
							String method = "tansitPartAndChildrenFactory";
							RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null,
									new Class[] { WTPart.class, String[].class }, new Object[] { part, partView });
							LOGGER.debug("Debug     RemoteMethodServer.ServerFlag...");

						} else {
							LOGGER.debug("Debug    运行转厂代码...");
							tansitPartAndChildrenFactory(part, partView);
							LOGGER.debug("Debug    完成转厂代码...");
						}
					}
				}

			} catch (WTException e) {
				e.printStackTrace();
			} catch (RemoteException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		} else {
			LOGGER.debug("Debug   参数个数不对...");
		}

	}
}
